from sqlalchemy import Column, String, Integer, DateTime, ForeignKey, Text, Enum as SQLEnum, Boolean
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.models.database import Base
import enum

class DocumentStatus(str, enum.Enum):
    """文档状态枚举"""
    UPLOADING = "UPLOADING"  # 上传中
    PROCESSING = "PROCESSING"  # 处理中
    COMPLETED = "COMPLETED"  # 完成
    FAILED = "FAILED"  # 失败

class Document(Base):
    """文档模型"""
    __tablename__ = "documents"

    id = Column(String(36), primary_key=True, index=True)
    title = Column(String(255), nullable=False, index=True)
    file_name = Column(String(255), nullable=False)
    file_path = Column(String(512), nullable=False)
    file_type = Column(String(50), nullable=False)
    file_size = Column(Integer, nullable=False)
    file_hash = Column(String(64), index=True)  # MD5哈希
    
    # 分类和知识库
    category_id = Column(String(36), ForeignKey('categories.id', ondelete='SET NULL'), nullable=True)
    knowledge_base_id = Column(String(36), ForeignKey('knowledge_bases.id', ondelete='SET NULL'), nullable=True)
    
    # 标签
    tags = Column(Text)  # JSON格式存储标签数组
    
    # 上传用户
    upload_user_id = Column(String(36), ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
    upload_user_name = Column(String(100))
    
    # 状态和时间
    status = Column(SQLEnum(DocumentStatus), default=DocumentStatus.UPLOADING, nullable=False)
    upload_time = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # OCR和处理信息
    ocr_status = Column(String(50))  # OCR处理状态
    page_count = Column(Integer)  # 页数
    word_count = Column(Integer)  # 字数
    summary = Column(Text)  # AI生成的摘要
    
    # 向量化状态
    is_vectorized = Column(Boolean, default=False)
    vector_store_id = Column(String(100))  # 向量库中的ID
    
    # 提取的文本内容
    extracted_text = Column(Text)  # OCR或文档解析后的文本内容
    
    # 元数据
    extra_metadata = Column(Text)  # JSON格式存储额外元数据
    
    # 关系
    shares = relationship("DocumentShare", back_populates="document", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<Document(title='{self.title}', status='{self.status}')>"
